<?php

/*
 * 微商城订单控制器
 * @author <!--blakefan 1621743934@qq.com -->
 */
namespace Home\Controller;
use Think\Controller;
class OrderController extends HomeController 
{
	/**
     * 订单列表
     * @param openid or uid
     */
	public function index()
	{
        ////获取所有的订单
        ///获取用户id
        $id=!empty($_SESSION['uid'])?$_SESSION['uid']:0;
        $page=I("get.page",1,'strip_tags');
        $count=M('order a')->join("cart_order_item b on a.orderid=b.orderid")->where("a.uid='%d'",$id)->count();
      $pagearr= getPageArr($page,C('PAGESIZE'),$count);
       $result=M('order a')
       ->join("cart_order_item b on a.orderid=b.orderid")
       ->order("create_time")
       ->where("a.uid='%d'",$id)
       ->limit($pagearr['start'],$pagearr['pagesize'])
       ->getField('a.orderid,a.create_time,a.address,a.province,a.order_amount,a.consignee,a.deviceid,b.supperid,a.settlestatus,a.pay_type,a.shipping_status,a.pay_status,a.order_status,b.number,b.price,b.productid,b.itemname,b.specvale,b.activprice,b.itemid');
        ///计算订单状态
       foreach($result as $k=>$v)
       {
         $result[$k]['orderstatus']=intval($v['order_status'])+intval($v['pay_status'])+intval($v['shipping_status']);
         $result[$k]['img']=M('item')->where("itemid='%d'",$v['itemid'])->getField("itemimg");
       }
      
       ////已付款未付款的订单
		$payment=array();
		$unpay=array();

       foreach($result as $key=>$val)
       {
         if($val['orderstatus']>=3)
         {
           $payment[]=$result[$key];///已经付款
         }
         if($val['orderstatus']<3 && $val['orderstatus']!=2)
         {
           $unpay[]=$result[$key];///未付款
         }
        

       }
   
       $this->assign("all",$result)->assign("payment",$payment)->assign("unpay",$unpay);
        $this->assign("pagearr",$pagearr);
       $this->display();
       }
	//生成订单
	public function createOrder()
	{
		
		//检测用户信息、购物车id 
		$uid=!empty($_SESSION['uid'])?$_SESSION['uid']:0;
		$cartid=$_COOKIE['ids'];
		if(!empty($cartid))
		{
			$cartid=explode(',',$cartid);
		}else
		{
			//当从前台读取的购物车产品为空，尝试从数据库读取
			$cartid=M('shipping_cart')->where('uid=%d',$uid)->getField('id',true);
		}
		
		
		if(empty($cartid) || empty($uid)){	echo "<script language='javascript'>alert('参数错误提示')</script>";return '';}
		//获取选中的购物车产品及默认地址
		$result='';
		$order=D('Order');
		$result=$order->index($cartid);
		$this->assign('iteminfo',$result['iteminfo']);//商品信息
		$this->assign('userinfo',$result['userinfo']);//用户信息
		$this->assign('countprice',$result['countprice']); //商品总价
		
		$this->display('createOrder');
	}
	//确认订单
	public function confirmOrder()
	{

		$result='';
		$mycart=!empty($_SESSION['mycart'])?$_SESSION['mycart']:'';
		$uid=!empty($_SESSION['uid'])?$_SESSION['uid']:0;
		
		if(empty($mycart))
		{
			$result['status']=0;
			$result['msg']='系统繁忙，请稍后再试';
			echo json_encode($result);
			return '';
		}
		//收货人信息
		$data['consignee']=I('post.consignee','','strip_tags');
		$data['mobile']=I('post.mobile','','strip_tags');
		$data['province']=I('post.province','','strip_tags');
		$data['city']=I('post.city','','strip_tags');
		$data['district']=I('post.county','','strip_tags');
		$data['address']=I('post.address','','strip_tags');
		$data['order_status']=0;
		$data['shipping_status']=0;
		$data['pay_status']=0;
		$data['order_sn']=getOrderSn();
		$data['uid']=$uid;
		//获取商品总金额
		$shipping_cart=M('shipping_cart');
		$map['uid']=$uid;
		$map['id']=array('in',$mycart);
		$data['order_amount']=$shipping_cart->where($map)->sum('totalprice');
		$data['create_time']=time();
		$data['areatype']=2;// 微信端商品所在区域：网购区

		//获取订单中商品信息
		
		$cartItem=$shipping_cart->where($map)->getField('id,itemname,itemid,productid,number');
		
		if(empty($cartItem))
		{
			$result['status']=2;
			$result['msg']='购物车为空';
			echo json_encode($result);
			return '';
		}
		
		$orderitem=array();
		
		foreach ($cartItem as $key => $value) 
		{	
			
			$value['itemid']=intval($value['itemid']);

			$orderitem[$key]['itemid']=$value['itemid'];
			$orderitem[$key]['itemname']=$value['itemname'];
			$orderitem[$key]['number']=$value['number'];
			$orderitem[$key]['productid']=$value['productid'];

			if(!empty($value['productid']))
			{	//productid 
				$productid=intval($value['productid']);
				$temp=M()->query('select price,color,supprice from '.C('DB_PREFIX').'product where productid='.$productid);

				$orderitem[$key]['price']=$temp[0]['price'];
				$orderitem[$key]['supperprice']=$temp[0]['supprice'];
				$orderitem[$key]['specvale']=$temp[0]['color'];	//规格
				}else
				{
					$itemid=intval($value['itemid']);
					$temp=M()->query('select price,supperprice from '.C('DB_PREFIX').'item where itemid='.$itemid);
					$orderitem[$key]['price']=$temp[0]['price'];
					$orderitem[$key]['supperprice']=$temp[0]['supperprice'];
				}

				//获取公共信息（型号，供应商，品牌）
				$orderitem[$key]['sn']=M('item')->where('itemid=%d',$value['itemid'])->getField('bn');
				$orderitem[$key]['brand']=M('item a')->join('inner join '.C('DB_PREFIX').'brand b on a.brandid=b.brandid')
											->where('a.itemid=%d',$value['itemid'])
											->getField('brandname');
				$orderitem[$key]['supperid']=M('item a ') ->where('a.itemid=%d',$value['itemid'])->getField('supperid ');	
		}
		
		//保存订单信息
		$order=M('order');
		$orderItem=M('order_item');
		$order->startTrans();
		$orderid=$order->data($data)->add();
		
		//保存订单商品信息
		foreach($orderitem as $key=>&$value)
		{
			$value['orderid']=$orderid;
			$temp2=$orderItem->add($value);
		}
	
		if($orderid && $temp2)
		{
			$order->commit();
			//生成订单成功->删除购物车
			$shipping_cart=M('shipping_cart');
			if(!empty($mycart))
			{
				$condition['id']=array('in',$mycart);
				$shipping_cart->where($condition)->delete();
			}
			$result['status']=1;
			$result['msg']='success';
			$result['orderid']=$orderid;
			echo json_encode($result);
			return '';

		}else{
			$order->rollback();
			$result['status']=0;
			$result['msg']='系统繁忙，请稍后再试';
			echo json_encode($result);
			return '';
		}
		

	}
	/*
	 *支付订单
	 *@param orderid
	 *return view
	 */
	public function payStyle()
	{
		$orderid=I('get.orderid',0,'strip_tags');
		$_SESSION['uid']=!empty($_SESSION['uid'])?$_SESSION['uid']:1;
		$uid=!empty($_SESSION['uid'])?$_SESSION['uid']:0;
		//获取订单总金额
		$order=M('order');
		$map['orderid']=$orderid;
		$map['uid']=$uid;
		$order=$order->where($map)->getField('orderid,order_sn,order_amount');
		$this->assign('order',$order[$orderid]);
		$this->display('pay');

	}
	/**
	 * 取消订单
	 */
	public function cancel()
	{
      $where['orderid']=I('get.id','','strip_tags');
    
      $status=M('order')->where($where)->setField("order_status",'2');
         
      if($status!==false)
      {
           echo '1';////订单取消成功
      }else{
      	echo '2';////失败
      }


	}


	/**
	 * 未支付订单
	 */
	public function unpay()
	{
       $id=M('user')->where("openid='%s'",$_SESSION['openid'])->getField("uid");
       
        $page=I("get.page",1,'strip_tags');
        $count=M('order a')->join("cart_order_item b on a.orderid=b.orderid")->where("a.uid='%d'",$id)->count();
        $pagearr= getPageArr($page,C('PAGESIZE'),$count);
       $result=M('order a')
       ->join("cart_order_item b on a.orderid=b.orderid")
       ->order("create_time")
       ->where("a.uid='%d'",$id)
       ->limit($pagearr['start'],$pagearr['pagesize'])
       ->getField('a.orderid,a.create_time,a.address,a.province,a.order_amount,a.consignee,a.deviceid,b.supperid,a.settlestatus,a.pay_type,(a.shipping_status+a.pay_status+a.order_status) as orderstatus, b.number,b.price,b.productid,b.itemname,b.specvale,b.activprice,b.itemid');    
         $unpay=array();
       foreach($result as $k=>$v)

       {    $result[$k]['img']=M('item')->where("itemid='%d'",$v['itemid'])->getField("itemimg");
           if($v['orderstatus']<3 && $v['orderstatus']!=2)
           {  
               $unpay[]=$result[$k];
           }
       }
        
     $this->assign("unpay",$unpay)->assign("pagearr",$pagearr);
     $this->display("");
	}
	/**
	 * 已经支付订单
	 */
		public function payment()
	{
       $id=M('user')->where("openid='%s'",$_SESSION['openid'])->getField("uid");
       
        $page=I("get.page",1,'strip_tags');
        $count=M('order a')->join("cart_order_item b on a.orderid=b.orderid")->where("a.uid='%d'",$id)->count();
        $pagearr= getPageArr($page,C('PAGESIZE'),$count);
       $result=M('order a')
       ->join("cart_order_item b on a.orderid=b.orderid")
       ->order("create_time")
       ->where("a.uid='%d'",$id)
       ->limit($pagearr['start'],$pagearr['pagesize'])
       ->getField('a.orderid,a.create_time,a.address,a.province,a.order_amount,a.consignee,a.deviceid,b.supperid,a.settlestatus,a.pay_type,(a.shipping_status+a.pay_status+a.order_status) as orderstatus, b.number,b.price,b.productid,b.itemname,b.specvale,b.activprice,b.itemid');    
      
         $payment=array();
       foreach($result as $k=>$v)
       {      $result[$k]['img']=M('item')->where("itemid='%d'",$v['itemid'])->getField("itemimg");
           if($v['orderstatus']>=3)
           {
               $payment[]=$result[$k];
           }
       }
     $this->assign("payment",$payment)->assign("pagearr",$pagearr);
     $this->display("");
	}

}